import jwt_decode from "jwt-decode";
import { nowTimeStamp } from "./time";
import { User } from "../types";

export function decodeJwtToken(token: string): User {
  let result: User = { mobile: "", openid: "" };
  try {
    result = jwt_decode(token);
  } catch (e) {
    console.log("jwt decode error:", e);
  }

  return result;
}

export function isValidToken(token: string): boolean {
  try {
    if (token == null || token == "") return false;
    const decodedToken = decodeJwtToken(token);
    if (decodedToken.mobile == "") {
      return false;
    } else if ((decodedToken as any).exp && (decodedToken as any).iat) {
      // 检查是否过期
      return nowTimeStamp() < (decodedToken as any).exp;
    }
  } catch (e) {
    return false;
  }

  return true;
}
